package com.hontech.kaltaapp.ui

import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.hontech.kaltaapp.R
import com.hontech.kaltaapp.app.Init
import com.hontech.kaltaapp.ui.fragment.CookingConfigFragment
import com.hontech.kaltaapp.ui.fragment.CookingFragment
import com.hontech.kaltaapp.ui.fragment.SettingFragment
import com.hontech.kaltaapp.ui.fragment.Status2Fragment
import com.hontech.kaltaapp.ui.fragment.StatusFragment
import com.hontech.kaltaapp.utils.runOnUi

// 1280*752
class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        TabInit(this)
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            runOnUi { Init.init() }
        }
    }
}

private class TabInfo(
    val text: String,
    val iconId: Int,
    val fragment: Fragment
)


private class TabInit(activity: MainActivity) : FragmentStateAdapter(activity) {

    private val tabInfos = arrayOf<TabInfo>(
        TabInfo("设置", R.drawable.ic_setting, SettingFragment()),
        TabInfo("状态", R.drawable.ic_setting, StatusFragment()),
        TabInfo("状态2", R.drawable.ic_setting, Status2Fragment()),
        TabInfo("配置", R.drawable.ic_setting, CookingConfigFragment()),
        TabInfo("煮面", R.drawable.ic_setting, CookingFragment())
    )

    init {
        val vp2 = activity.findViewById<ViewPager2>(R.id.id_main_vp2)
        val tabs = activity.findViewById<TabLayout>(R.id.id_main_tablayout)
        vp2.adapter = this
        vp2.offscreenPageLimit = tabInfos.size
        TabLayoutMediator(tabs, vp2, true, false) { tab, index ->
            tab.text = tabInfos[index].text
            tab.setIcon(tabInfos[index].iconId)
        }.attach()
        vp2.isUserInputEnabled = false
    }

    override fun getItemCount(): Int {
        return tabInfos.size
    }

    override fun createFragment(position: Int): Fragment {
        return tabInfos[position].fragment
    }
}